package Hot100;

import Tree.TreeNode;

import java.util.Deque;
import java.util.LinkedList;

public class 对称二叉树 {
    public boolean isSymmetric(TreeNode root) {
        // 迭代
        Deque<TreeNode> deque = new LinkedList<>();
        deque.offerFirst(root.left);
        deque.offerLast(root.right);
        while (!deque.isEmpty()) {
            TreeNode leftNode = deque.pollFirst();
            TreeNode rightNode = deque.pollLast();
            if (leftNode == null && rightNode == null) continue;
            if (leftNode == null || rightNode == null || leftNode.val != rightNode.val) return false;
            deque.offerFirst(leftNode.left);
            deque.offerFirst(leftNode.right);
            deque.offerLast(rightNode.right);
            deque.offerLast(rightNode.left);
        }
        return true;

        // 递归
        /*return compare(root.left, root.right);*/
    }

    private boolean compare(TreeNode left, TreeNode right) {
        if (left == null) return right == null;
        else if (right == null) return false;
        else if (left.val != right.val) return false;
        else return compare(left.left, right.right) && compare(left.right, right.left);
    }
}
